package GinSrv

import (
	"fmt"
	projectConfig "gin-service/config"
	"gin-service/controller"
	"gin-service/lib/GinSrv/GinRouter"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Cors() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		method := ctx.Request.Method

		ctx.Header("Access-Control-Allow-Origin", "*")
		ctx.Header("Access-Control-Allow-Headers", "Content-Type, AccessToken, X-CSRF-Token, Authorization, Token")
		ctx.Header("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS")
		ctx.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		ctx.Header("Access-Control-Allow-Credentials", "true")
		ctx.Header("Access-Control-Allow-Headers", "X-Custom-Header")

		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			ctx.AbortWithStatus(http.StatusNoContent)
		}
		// 处理请求
		ctx.Next()
	}
}

func GinInit(callback func(engine *gin.Engine), config interface{}) {
	if projectConfig.GlobalRunningEnv != "production" {
		gin.SetMode(gin.DebugMode)
	} else {
		gin.SetMode(gin.ReleaseMode)
	}

	ginEngine := gin.Default()
	ginEngine.Use(Cors())

	callback(ginEngine)

	ginConfig := config.(map[string]interface{})
	port := ginConfig["port"]
	err := ginEngine.Run(fmt.Sprintf(":%s", port))
	if err != nil {
		panic(fmt.Sprintf("gin error: %s", err.Error()))
	}
}

func RoutersCollect(ginEngine *gin.Engine) {
	controller.TestController(ginEngine)
	controller.UserController(&GinRouter.GroupRouter{GinEngine: ginEngine, Path: "/user"})
	//controller.UploadController(&GinRouter.BaseRouter{GinEngine: ginEngine})
	controller.DemoController(&GinRouter.GroupRouter{GinEngine: ginEngine, Path: "/demo"})
	controller.WorkController(&GinRouter.GroupRouter{GinEngine: ginEngine, Path: "/work"})
	controller.OrderController(&GinRouter.GroupRouter{GinEngine: ginEngine, Path: "/order"})

	controller.ErcUserController(&GinRouter.GroupRouter{GinEngine: ginEngine, Path: "/erc/user"})
	controller.ErcSupplierController(&GinRouter.GroupRouter{GinEngine: ginEngine, Path: "/erc/supplier"})
	controller.ErcCustomerController(&GinRouter.GroupRouter{GinEngine: ginEngine, Path: "/erc/customer"})
}
